package com.yu.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yu.constant.JwtClaimsConstant;
import com.yu.model.Result;
import com.yu.model.dto.DoctorDTO;
import com.yu.model.dto.DoctorPageDTO;
import com.yu.model.dto.PatientDTO;
import com.yu.model.entity.Doctor;
import com.yu.model.entity.Patient;
import com.yu.properties.JwtProperties;
import com.yu.service.DoctorService;
import com.yu.service.PatientService;
import com.yu.utils.JwtUtil;
import com.yu.utils.StatusHolder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
@Slf4j
@RestController
@Api(tags = "医生相关接口")
@RequestMapping("/doctor")
public class DoctorController {

    @Resource
    private DoctorService doctorService;

    @Resource
    private PatientService patientService;

    @Resource
    private JwtProperties jwtProperties;

    @PostMapping("/login")
    @ApiOperation(value = "医生登录")
    public Result<String> login(@RequestBody DoctorDTO doctorDTO) {

        log.info("doctorDTO:{}", doctorDTO);
        String password = DigestUtils.md5DigestAsHex(doctorDTO.getPassword().getBytes());
        LambdaQueryWrapper<Doctor> doctorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        doctorLambdaQueryWrapper.eq(doctorDTO.getPhone() != null, Doctor::getPhone, doctorDTO.getPhone());
        Doctor one = doctorService.getOne(doctorLambdaQueryWrapper);
        if (one == null) {
            return Result.error("账号不存在");
        }
        if (!one.getPassword().equals(password)) {
            return Result.error("密码或账号错误");
        }
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.DOC_ID, one.getId());
        claims.put("status","doctor");
        String jwt = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        StatusHolder.saveStatus("doctor");
        return Result.success(jwt);
    }




    @GetMapping("/patient/{id}")
    @ApiOperation(value = "根据病人id查询病人信息")
    public Result<Patient> getPatient(@PathVariable("id") Long id){
        return Result.success(doctorService.getPatient(id));
    }


    @PutMapping("/patient")
    @ApiOperation(value = "根据病人id修改病人信息（这里单纯给出治疗意见）")
    public Result<String> modifyPatient(@RequestBody Patient patient){
        patientService.modifyPatient(patient);
        return Result.success("修改成功");
    }





}
